from flask import jsonify,request,render_template,redirect,session
from flask_login import login_required

from redash.handlers.api import api
from redash.handlers.base import routes
from redash.monitor import get_status
from redash.permissions import require_super_admin
from redash.security import talisman
from redash.models.users import User
from redash.settings import MULTI_ORG, HOST


@routes.route("/ping", methods=["GET"])
@talisman(force_https=False)
def ping():
    return "PONG."


if MULTI_ORG:
    @routes.route("/", methods=["GET","POST"])
    def myindex():
        if request.method == "GET" and session.get("user_id") == None:
            return render_template("multi_org_input.html", base_url=HOST)

        try:
            user_id = int(session.get("user_id").split("-")[0])
            org_slug = User.get_by_id(user_id).org.slug
            path = "/" + str(org_slug)
        except:
            path = "/" + str(request.form.get("org_slug"))
        return redirect(path)


@routes.route("/status.json")
@login_required
@require_super_admin
def status_api():
    status = get_status()
    return jsonify(status)


def init_app(app):
    from redash.handlers import (
        embed,
        queries,
        static,
        authentication,
        admin,
        setup,
        organization,
    )

    app.register_blueprint(routes)
    api.init_app(app)
